package com.hucheng.rest.base;

import com.alibaba.fastjson.JSONObject;
import com.hucheng.common.exception.EduException;
import com.hucheng.common.request.ServiceCoreQuery;
import com.hucheng.common.response.ServiceCoreVO;
import com.hucheng.common.utils.CommonUtils;
import com.hucheng.common.utils.ReadPropertiesUtils;
import com.hucheng.common.utils.TimeUtils;
import com.hucheng.common.utils.ValidatorUtils;
import com.hucheng.rest.validator.HttpApiCheck;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Properties;

/**
 * @Author: 凉白开不加冰
 * @Version: 0.0.1V
 * @Date: 2019-06-26
 * @Description: 请求处理
 **/
@Slf4j
public class BaseService {

    /**
     * 返回结果封装类
     */
    protected ServiceCoreVO serviceCoreVO = null;
    /**
     * 请求封装类
     */
    protected ServiceCoreQuery serviceCoreQuery = null;
    /**
     * 错误码内容
     */
    private static final Properties properties = ReadPropertiesUtils.getProperties("message.properties");

    /**
     * 初始化
     */
    protected void init(ServiceCoreQuery serviceCoreQuery) {
        String requestTime = TimeUtils.getSysTime();
        serviceCoreQuery.setRequestTime(requestTime);
        this.serviceCoreQuery = serviceCoreQuery;
        String action = serviceCoreQuery.getAction();
        this.serviceCoreQuery.setBean(action.split("_")[0] + "Action");
        this.serviceCoreQuery.setMethod(action.split("_")[1] + "V100");
    }

    /**
     * 请求响应
     *
     * @return
     */
    public ServiceCoreVO response(ServiceCoreQuery serviceCoreQuery, HttpServletRequest request, StringRedisTemplate stringRedisTemplate) throws EduException {
        init(serviceCoreQuery);
        Long startTime = System.currentTimeMillis();
        try {
            //校验请求信息
            HttpApiCheck.getHttpApiCheck(serviceCoreQuery, request, stringRedisTemplate).checkRequest();
            //执行方法
            execute();
        } catch (EduException e) {
            e.printStackTrace();
            if (ValidatorUtils.isDigital(e.getMessage())) {
                int code = Integer.valueOf(e.getMessage());
                serviceCoreVO = new ServiceCoreVO(code);
            } else {
                serviceCoreVO = new ServiceCoreVO(e.getMessage());
            }
        }

        Long endTime = System.currentTimeMillis();

        serviceCoreQuery.setConsumeMilSecond((endTime - startTime) + "ms");
        printAPIInfo(serviceCoreVO, this.serviceCoreQuery);
        return serviceCoreVO;
    }

    /**
     * 调用执行方法
     *
     * @throws EduException
     */
    private void execute() throws EduException {
        if (ValidatorUtils.isEmpty(serviceCoreQuery.getBean())) {
            throw new EduException(110005);
        }

        BaseAction action = new BaseAction();
        serviceCoreVO = action.execute(serviceCoreQuery);
    }

    /**
     * 打印请求日志
     *
     * @param scvo
     * @param serviceCoreQuery
     */
    public static void printAPIInfo(ServiceCoreVO scvo, ServiceCoreQuery serviceCoreQuery) {
        StringBuffer sb = new StringBuffer();
        if (scvo.getCode() == 0 || scvo.getCode() == 100000) {
            sb.append(" [INFO]==>");
        } else {
            sb.append(" [ERROR]==>");
        }
        sb.append(Thread.currentThread().getName() + ":");
        sb.append(";method-->" + serviceCoreQuery.getBean() + "_" + serviceCoreQuery.getMethod());
        sb.append(";access_id-->" + serviceCoreQuery.getAccessId());
        sb.append(";userId-->" + serviceCoreQuery.getUserId());
        sb.append(";request_time-->" + serviceCoreQuery.getRequestTime());
        sb.append(";complete_time-->" + TimeUtils.getSysTime());
        sb.append(";code-->" + scvo.getCode());
        String msg = scvo == null ? properties.getProperty(scvo.getCode() + "") : scvo.getMessage();
        sb.append(";msg-->" + msg);
        sb.append(";format-->" + serviceCoreQuery.getFormat());
        sb.append(";sign-->" + serviceCoreQuery.getSign());
        JSONObject content = JSONObject.parseObject(JSONObject.toJSONString(serviceCoreQuery.getReqObject()));
        if (content.containsKey("password")) {
            content.put("password", CommonUtils.loginPwd(content.getString("password")));
        }
        sb.append(";content-->" + content);
        sb.append(";consume-->" + serviceCoreQuery.getConsumeMilSecond());
        log.info(sb.toString());
    }

}
